# coding=UTF-8
import time
import picamera
import uuid
from datetime import datetime
class CamService(object):

    # 创建文件名，传入扩展名
    def create_name(self, extraname='jpg'):
        return str(uuid.uuid1())+"."+extraname

    # 创建时间文件名，传入扩展名
    def create_name_by_time(self,extraname='jpg'):
        now = datetime.now()
        return now.strftime('%Y%m%d%H%M%S%f')+"."+extraname

        # 创建一个普通照片, 传入存储路径，图片宽度,高度，保存格式
    def get_img(self, uri, width=2048, height=1536, extraname="jpg"):
        with picamera.PiCamera() as camera:
            camera.resolution = (width, height)
            camera.start_preview()
            # 关闭LED指示
            camera.led = False
            # 摄像头预热2秒
            time.sleep(1)
            temp_name = uri+self.create_name_by_time(extraname)
            camera.capture(temp_name)
            return temp_name

    # 创建一个连拍，传入存储路径，图片宽度,高度，保存格式，延迟时间,拍摄张数
    def get_img_continuous(self, uri, width=1024, height=768, extraname="jpg", wait_time=5, num=5):
        with picamera.PiCamera() as camera:
            camera.resolution = (width, height)
            # 关闭LED指示
            camera.led = False
            camera.start_preview()
            img_list = []
            time.sleep(1)
            try:

                for i, filename in enumerate(
                        camera.capture_continuous(uri+'{timestamp:%Y%m%d%H%M%S%f}.'+extraname)):
                    img_list.append(filename)
                    time.sleep(wait_time)
                    if i == num-1:
                        break
            finally:
                camera.stop_preview()
                return img_list

    # 创建一个快速连拍,可以指定iso，传入存储路径，图片宽度,高度，保存格式，延迟时间,拍摄张数
    def get_img_sequence(self, uri, width=1024, height=768, extraname="jpg", num=5, iso=100):
        with picamera.PiCamera() as camera:
            camera.resolution = (width, height)
            # 关闭LED指示
            camera.led = False
            camera.iso = iso
            now = datetime.now()
            temp_name = now.strftime('%Y%m%d%H%M%S')
            img_list = []
            for i in range(0, num):
                img_list.append(uri+temp_name+str(i)+"."+extraname)
            camera.start_preview()
            time.sleep(1)
            camera.capture_sequence(img_list)
            camera.stop_preview()
            return img_list

    def get_video(self,uri, width=640, height=480, extraname="h264", video_length=10):
        with picamera.PiCamera() as camera:
            camera.resolution = (width, height)
            camera.start_recording(uri+self.create_name_by_time(extraname))
            camera.wait_recording(video_length)
            camera.stop_recording()

    def res_name(self, path):
        return path.split("/")[-1]

if __name__ == '__main__':
    cam = CamService()
    cam.get_img("/home/pi/Pictures/Camera/")
    time.sleep(2)
    cam.get("/home/pi/Pictures/Camera/", iso=800)
    # clist = user.getChargeList()
    # rlist = user.getenewRList()

